<template>
   <div class="app-container">
      <a-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" layout="inline">
         <a-form-item label="户主姓名" field="headName">
            <a-input
               v-model="queryParams.headName"
               placeholder="请输入户主姓名"
               clearable
               style="width: 240px"
               @keyup.enter="handleQuery"
            />
         </a-form-item>
        <a-form-item label="所在片区" field="areaId">
          <a-select v-model="queryParams.areaId" placeholder="请选择">
            <a-option
                v-for="dict in bis_area_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></a-option>
          </a-select>
        </a-form-item>
         <a-form-item label="创建时间" style="width: 308px">
            <a-range-picker
               v-model="dateRange"
               value-format="YYYY-MM-DD"
               type="daterange"
               range-separator="-"
               start-placeholder="开始日期"
               end-placeholder="结束日期"
            ></a-range-picker>
         </a-form-item>
         <a-form-item>
            <a-button type="primary" class="button-margin-right" @click="handleQuery">
              <template #icon>
                <icon-Search/>
              </template>
              搜索
            </a-button>
            <a-button  @click="resetQuery">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
         </a-form-item>
      </a-form>

      <a-row :gutter="10" class="mb8">
         <a-col :span="1.5">
            <a-button
               type="primary"
               plain
               @click="handleAdd"
               v-hasPermi="['system:dict:add']"
            >
              <template #icon>
                <icon-plus/>
              </template>
              新增
            </a-button>
         </a-col>
         <a-col :span="1.5">
            <a-button
               status="success"
               type="primary"
               plain
               :disabled="single"
               @click="handleUpdate"
               v-hasPermi="['system:dict:edit']"
            >
              <template #icon>
                <icon-edit/>
              </template>
              修改
            </a-button>
         </a-col>
         <a-col :span="1.5">
            <a-button
               status="danger"
               type="primary"
               plain
               :disabled="multiple"
               @click="handleDelete"
            >
              <template #icon>
                <icon-delete/>
              </template>
              删除
            </a-button>
         </a-col>
         <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </a-row>

      <a-table v-loading="loading" :data="typeList"
               row-key="id" :row-selection="rowSelection"
               v-model:selectedKeys="selectedIds" :pagination="false"
               @selection-change="handleSelectionChange">
        <template #columns>
          <a-table-column title="家庭编号" align="center" :show-overflow-tooltip="true">
            <template #cell="{record}">
              <router-link :to="'/grid/housekeeper-data/index/' + record.id" class="link-type">
                <span>{{ record.id }}</span>
              </router-link>
            </template>
          </a-table-column>
          <a-table-column data-index="resultStatus" title="所在片区" width="100">
            <template #cell="{record}">
              <dict-tag :options="bis_area_type" :value="record.areaId" />
            </template>
          </a-table-column>
          <a-table-column title="网格管理员" align="center" data-index="areaName" :show-overflow-tooltip="true"/>
          <a-table-column title="家庭地址" align="center" data-index="address" :show-overflow-tooltip="true"/>
          <a-table-column title="户主姓名" align="center" data-index="headName" :show-overflow-tooltip="true"/>
          <a-table-column title="联系方式" align="center" data-index="contact" :show-overflow-tooltip="true"/>
          <a-table-column title="创建时间" align="center" data-index="createTime" width="180"/>
          <a-table-column title="操作" align="center" class-name="small-padding fixed-width">
            <template #cell="{record}">
              <a-button
                  type="text"
                  @click="handleView(record)"
              >
                <icon-edit/>
                查看
              </a-button>
              <a-button
                  type="text"
                  @click="handleUpdate(record)"
              >
                <icon-edit/>
                修改
              </a-button>
              <a-button
                  type="text"
                  @click="handleDelete(record)"
              >
                <icon-delete/>
                删除
              </a-button>
            </template>
          </a-table-column>
        </template>

      </a-table>

     <!--分页-->
     <div style="margin-top: 30px;float: right">
       <a-pagination :total="total" show-total show-jumper show-page-size
                     v-model:current="queryParams.pageNum"
                     v-model:page-size="queryParams.pageSize"
                     @change="onPageChange"
                     @page-size-change="onPageSizeChange"
       />
     </div>

      <!-- 添加或修改家庭对话框 -->
     <a-drawer :visible="dictDrawerVisible" @ok="handleDictOk" @cancel="handleDictCancel" unmountOnClose :width="540">
       <template #title>
         <h4>{{title}}</h4>
       </template>
       <a-form ref="dictRef" :model="form" :rules="rules" label-width="80px">
         <a-form-item label="家庭地址" field="address">
           <a-input v-model="form.address" placeholder="请输入家庭地址" />
         </a-form-item>
         <a-form-item label="所在片区" field="areaId">
           <a-select v-model="form.areaId" placeholder="请选择">
             <a-option
                 v-for="dict in bis_area_type"
                 :key="dict.value"
                 :label="dict.label"
                 :value="dict.value"
             ></a-option>
           </a-select>
         </a-form-item>
         <a-form-item label="小区经度" field="communityLongitude">
           <a-input v-model="form.communityLongitude" placeholder="请输入小区经度" />
         </a-form-item>
         <a-form-item label="小区纬度" field="communityLatitude">
           <a-input v-model="form.communityLatitude" placeholder="请输入小区纬度" />
         </a-form-item>
         <a-form-item label="户主姓名" field="headName">
           <a-input v-model="form.headName" placeholder="请输入户主姓名" />
         </a-form-item>
         <a-form-item label="联系方式" field="contact">
           <a-input v-model="form.contact" placeholder="请输入联系方式" />
         </a-form-item>
         <a-form-item label="家庭情况" field="familyStatus">
           <a-textarea v-model="form.familyStatus" placeholder="请输入家庭情况" />
         </a-form-item>
         <a-form-item label="政府帮助" field="governmentAssistance">
           <a-textarea v-model="form.governmentAssistance" placeholder="请输入政府帮助情况" />
         </a-form-item>
         <a-form-item label="备注" field="remark">
           <a-textarea v-model="form.remark" placeholder="请输入内容"></a-textarea>
         </a-form-item>
       </a-form>
         <div style="height: 350px"><CoordSelector @mapClick="onMapClick" @addressSelected="onAddressSelected" :lon="form.communityLongitude" :lat="form.communityLatitude"/></div>
     </a-drawer>


       <!-- 查看家庭信息-->
     <a-drawer :visible="viewDrawerVisible" @ok="viewDrawerVisible=false" @cancel="viewDrawerVisible=false"  ok-text="关闭" hide-cancel  unmountOnClose :width="540">
       <template #title>
         <h4>查看人员信息</h4>
       </template>
       <a-form ref="dictRef" :model="form" :rules="rules" label-width="80px">
         <a-form-item label="家庭地址" field="address">
             <span>{{ form.address }}</span>
         </a-form-item>
         <a-form-item label="所在片区" field="address">
           <span>
              <dict-tag :options="bis_area_type" :value="form.areaId" />
            </span>
         </a-form-item>
         <a-form-item label="网格管理员" field="areaName">
           <span>{{ form.areaName }}</span>
         </a-form-item>
         <a-form-item label="小区经度" field="communityLongitude">
             <span>{{ form.communityLongitude }}</span>
         </a-form-item>
         <a-form-item label="小区纬度" field="communityLatitude">
             <span>{{ form.communityLatitude }}</span>
         </a-form-item>
         <a-form-item label="户主姓名" field="headName">
             <span>{{ form.headName }}</span>
         </a-form-item>
         <a-form-item label="联系方式" field="contact">
             <span>{{ form.contact }}</span>
         </a-form-item>
         <a-form-item label="家庭情况" field="familyStatus">
             <span>{{ form.familyStatus }}</span>
         </a-form-item>
         <a-form-item label="政府帮助" field="governmentAssistance">
             <span>{{ form.governmentAssistance }}</span>
         </a-form-item>
         <a-form-item label="备注" field="remark">
             <span>{{ form.remark }}</span>
         </a-form-item>
       </a-form>
        <div style="height: 350px"><MapLocation :lon="form.communityLongitude" :lat="form.communityLatitude"/></div>
     </a-drawer>



   </div>
</template>

<script setup name="Dict">
import {getBisFamilyInfoList,getBisFamily,addBisFamilyInfo,updateBisFamilyInfo,delBisFamilyInfo} from "@/api/grid/housekeeper";
import {getCurrentInstance, reactive, ref, toRefs} from "vue";
import MapLocation from './map-location'
import CoordSelector from './coord-selector'

const { proxy } = getCurrentInstance();

const { bis_area_type } = proxy.useDict("bis_area_type");

const typeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const dictDrawerVisible = ref(false);
const viewDrawerVisible = ref(false);
const direction = ref('rtl')
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    headName: undefined,
    areaId:undefined
  },
  rules: {
    address: [{ required: true, message: "家庭地址不能为空", trigger: "blur" }],
    communityLongitude: [{ required: true, message: "小区经度不能为空", trigger: "blur" }],
    communityLatitude: [{ required: true, message: "小区纬度不能为空", trigger: "blur" }],
    headName: [{ required: true, message: "户主姓名不能为空", trigger: "blur" }],
    contact: [{ required: true, message: "联系方式不能为空", trigger: "blur" }],
    familyStatus: [{ required: true, message: "家庭情况不能为空", trigger: "blur" }],
    governmentAssistance: [{ required: true, message: "政府帮助情况不能为空", trigger: "blur" }]
  },
});

const { queryParams, form, rules } = toRefs(data);

const handleDictOk = () => {
  submitForm()
};
const handleDictCancel = () => {
  dictDrawerVisible.value = false;
}
/** 开启表格多选  */
const selectedIds = ref([]);
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: false,
});
// 修改按钮生效
const single = computed(() => {
  return selectedIds.value.length !== 1
});
// 删除按钮生效
const multiple = computed(() => {
  return !selectedIds.value.length
});

const onPageChange = (current) => {
  queryParams.value.pageNum = current
  getList()
};
const onPageSizeChange = (pageSize) => {
  queryParams.value.pageSize = pageSize
  getList()
};

/** 查询字典类型列表 */
function getList() {
  queryParams.value.startTime = dateRange.value[0];
  queryParams.value.endTime = dateRange.value[1];
  loading.value = true;
  getBisFamilyInfoList(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    typeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  dictDrawerVisible.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    dictId: undefined,
    dictName: undefined,
    dictType: undefined,
    status: "0",
    remark: undefined
  };
  proxy.resetForm("dictRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  dictDrawerVisible.value = true;
  title.value = "添加人员信息";
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 查看按钮操作 */
function handleView(row) {
  reset();
  const id = row.id || ids.value;
  getBisFamily(id).then(response => {
    form.value = response.data;
    // console.log('form.value')
    // console.log(form.value)
    viewDrawerVisible.value = true;
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getBisFamily(id).then(response => {
    form.value = response.data;
    dictDrawerVisible.value = true;
    title.value = "修改人员信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["dictRef"].validate(valid => {
    if (!valid) {
      if (form.value.id !== undefined) {
        updateBisFamilyInfo(form.value).then(response => {
          proxy.$message.success("修改成功");
          dictDrawerVisible.value = false;
          getList();
        });
      } else {
        addBisFamilyInfo(form.value).then(response => {
          proxy.$message.success("新增成功");
          dictDrawerVisible.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const fIds = row.id || ids.value;
  proxy.$confirm('是否确认删除编号为"' + fIds + '"的数据项？').then(function() {
    return delBisFamilyInfo(fIds);
  }).then(() => {
    getList();
    proxy.$message.success("删除成功");
  }).catch(() => {});
}

getList();

function onMapClick(lnglat){
   form.value.communityLatitude = lnglat.lat + '';
   form.value.communityLongitude = lnglat.lon + '';
}
function onAddressSelected(obj){
   form.value.communityLatitude = obj.lat + '';
   form.value.communityLongitude = obj.lon + '';
   form.value.address = obj.district + obj.address + obj.name;
}
</script>
